import base64
import json
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex


a = '''{'name':'州的先生','url':'zmister.com','desc':'编程应用实战'}''' # 原始数据
k = 'zmistercomzmiste'.encode('utf-8')  # 密钥
iv = b'1234567890asdfgh'  # 偏移量
mode = AES.MODE_CBC  # 模式

def cryp_str(value):
    value = value.encode('utf-8') # 对数据进行utf-8编码
    cryptor = AES.new(k, mode, iv) # 创建一个新的AES实例
    length = 16
    count = len(value)
    # 如果数据长度小于密钥长度
    if count < length:
        add = (length - count)
        # \0 backspace
        text = value + ('\0' * add).encode('utf-8')
    elif count > length:
        add = (length - (count % length))
        text = value + ('\0' * add).encode('utf-8')
    ciphertext = cryptor.encrypt(text) # 加密字符串
    print("原始加密数据：",ciphertext)
    ciphertext_hex = b2a_hex(ciphertext) # 字符串转十六进制数据
    print("十六进制加密：",ciphertext_hex)
    ciphertext_hex_de = ciphertext_hex.decode()
    print("十六进制加密字符串：",ciphertext_hex_de)
    return ciphertext_hex_de

def decry_str(value):
    cryptor = AES.new(k, mode, iv) # 创建一个AES实例
    value_hex = a2b_hex(value) # 将十六进制数据转换为字符串
    plain_text = cryptor.decrypt(value_hex) # 对字符串进行解密
    print("解密数据：",plain_text)
    print('解码解密数据：',bytes.decode(plain_text).rstrip('\0'))
    return bytes.decode(plain_text).rstrip('\0')
